package com.rabbitmq.demo;

import com.rabbitmq.client.*;

import java.nio.charset.StandardCharsets;

/**
 * @ClassName ConsumerA
 * @Description 直连交换机消费者A
 * @Author Kx
 * @Date 2025/10/10 10:41
 * @Version 1.0
 */
public class ConsumerA {
    /**
     * 定义队列
     */
    private final static String QUEUE_ONE = "queue.one";

    /**
     * 定义交换机
     */
    private final static String EXCHANGE_NAME = "my.direct";

    /**
     * 连接工厂
     */
    private static ConnectionFactory connectionFactory;

    /**
     * @author: kx
     * @date: 2025/10/10 10:36
     * @param null
     * @return
     * @description: 初始化工厂
     */
    static {
        connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("localhost");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("kx");
        connectionFactory.setPassword("123456");
    }

    /**
     * @author: kx
     * @date: 2025/10/10 10:49
     * @description: 接收消息
    */
    public static void receive() {
        try {
            // 创建连接
            Connection connection = connectionFactory.newConnection();
            // 创建通信
            Channel channel = connection.createChannel();

            // 声明交换机及其类型
            channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.DIRECT);

            // 声明队列
            channel.queueDeclare(QUEUE_ONE, false, false, false, null);

            // 将交换机和队列结合路由key进行绑定
            // 参数三：路由key
            channel.queueBind(QUEUE_ONE, EXCHANGE_NAME, "my.key");

            // 接收消息
            DeliverCallback callback = (consumerTag, delivery) -> {
                // 获取消息（消息队列中的内容是字节数组，因此转换为 String）
                String message = new String(delivery.getBody(), StandardCharsets.UTF_8);
                System.out.println("消费者A 接收到消息：" + message);
            };

            // 订阅消息
            channel.basicConsume(QUEUE_ONE, true, callback, consumerTage -> {});
        } catch (Exception e) {
            throw new RuntimeException("读取失败" + e);
        }
    }

    public static void main(String[] args) {
        receive();
    }
}
